//package com.hb.medical_research_system.common;
//
//import io.jsonwebtoken.Jwt;
//import io.jsonwebtoken.JwtBuilder;
//import io.jsonwebtoken.Jwts;
//import io.jsonwebtoken.SignatureAlgorithm;
//
//
//import java.util.Date;
//import java.util.HashMap;
//import java.util.Map;
//
//public class JwtUtils {
//
//    private static final String jwtToken = ";20oifnamsdf58909*()*()#$^(@*#^$56461";
//
//    public static String createToken(Integer userId){
//        Map<String,Object> claims = new HashMap<>();
//        claims.put("userId",userId);
//        JwtBuilder jwtBuilder = Jwts.builder()
//                .signWith(SignatureAlgorithm.HS256, jwtToken) // 签发算法，秘钥为jwtToken
//                .setClaims(claims) // body数据
//                .setIssuedAt(new Date()) // 设置签发时间
//                .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 60 * 1000));// 一天的有效时间
//        String token = jwtBuilder.compact();
//        return token;
//    }
//
//    public static Map<String, Object> checkToken(String token){
//        try {
//            Jwt parse = Jwts.parser().setSigningKey(jwtToken).parse(token);
//            return (Map<String, Object>) parse.getBody();
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//}
package com.hb.medical_research_system.common;

import com.alibaba.druid.util.StringUtils;

import com.hb.medical_research_system.entity.User;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JWTUtils {
    //时效：24小时
    public static final long EXPIRE = 1000*60*60*24;
    // 签名哈希的密钥，对于不同的加密算法来说含义不同
    public static final String SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    /**
     * 根据用户id生成token
     * @param username 用户昵称
     * @return JWT规则生成的token
     */
    public static String getJwtToken(String username, Long userId){
        Map<String, Object> map = new HashMap<>();
        String Id = String.valueOf(userId);
        map.put("alg", "HS256");
        map.put("typ","JWT");
        String id = String.valueOf(userId);
        String JwtToken = Jwts.builder()
                .setHeader(map)
                .setIssuedAt(new Date())  //生成时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("username", username)
                .claim("userId", id)
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();

        return JwtToken;
    }

    /**
     * 获得body中的值
     * @param token
     * @return
     */
    public static User checkJwtToken(String token){
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(SECRET).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        User user = new User();

        String userId = (String) body.get("userId");
        Long realid = Long.parseLong(userId);

        user.setUserId(realid); //TODO 将Long存入body里,会变成Integer, 取出来,要转换Integer为Integer, 丢失精度报错, 神坑!
        user.setUsername((String) body.get("username"));
        return user;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken token字符串
     * @return 如果token有效返回true，否则返回false
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken))
            return false;
        try {
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request Http请求对象
     * @return 如果token有效返回true，否则返回false
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            // 从http请求头中获取token字符串
            String jwtToken = request.getHeader("token");
            if(StringUtils.isEmpty(jwtToken))
                return false;
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token获取id
     * @param request Http请求对象
     * @return 解析token后获得的用户id
     */
    public static String getMemberIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        if(StringUtils.isEmpty(jwtToken)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("id");
    }
}
